#include "head.h"


// 子进程通过本地socket, 获取某个新链接的客户端的socket对象的文件描述符
// 子进程接收父进程传过来的
int localRecvMsg(int local_socket, int * net_fd, int *flag){


    struct msghdr hdr;
    bzero(&hdr, sizeof(hdr));

    // 凑正文信息
    int * num = (int *)malloc(sizeof(int));
    struct iovec iov[1];
    iov[0].iov_base = num;
    iov[0].iov_len = sizeof(int);

    hdr.msg_iov = iov;
    hdr.msg_iovlen = 1;

    // 凑控制信息
    struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;
    
    hdr.msg_control = cms;
    hdr.msg_controllen = CMSG_LEN(sizeof(int));

    recvmsg(local_socket, &hdr, 0);

    void *p = CMSG_DATA(cms);

    *net_fd = *(int*)p;

    printf("num = %d\n",*num);
    *flag = *num;

    return  0;
}


// 通过本地socket: 把一个文件描述符所指向的文件信息
// 父进程传给子进程
int localSendMsg(int local_socket, int net_fd, int flag){


    struct msghdr hdr;
    bzero(&hdr, sizeof(hdr));

    // 凑正文信息
    struct iovec iov[1];
    iov[0].iov_base = &flag;
    iov[0].iov_len = sizeof(int);

    hdr.msg_iov = iov;
    hdr.msg_iovlen = 1;
    // 凑控制信息
    struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;

    void *p = CMSG_DATA(cms);
    int *num = (int *)p;
    *num = net_fd;

    hdr.msg_control = cms;
    hdr.msg_controllen = CMSG_LEN(sizeof(int));

    sendmsg(local_socket, &hdr, 0);

    return 0;
}
